#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
from selenium import webdriver
import time
import datetime
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
import re


# 输入时间区间
def time_legal():
    year = int(input('请输入年份：'))
    month = int(input('请输入月份：'))
    day = int(input('请输入天份：'))
    x = [[0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]
    if month < 1 or month > 12:
        print('month must be in 1..12')
        exit(1)
    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        if day < 1 or day > x[0][month]:
            print('日期不正确')
            exit(1)
    else:
        if day < 1 or day > x[1][month]:
            print('日期不正确')
            exit(1)
    date = datetime.date(year, month, day)
    return date


def gettime(c_time):
    cur = c_time.split('-')
    if len(cur) == 1:
        if '昨天' in cur[0]:
            cur_t = datetime.date.today() - datetime.timedelta(days=1)
        elif '小时' in cur[0]:
            localtime = time.localtime(time.time())
            temp = re.findall(r'(.*?)小时', cur[0])
            if int(temp[0]) > localtime.tm_hour:
                cur_t = datetime.date.today() - datetime.timedelta(days=1)
            else:
                cur_t = datetime.date.today()
        elif '分钟' in cur[0]:
            localtime = time.localtime(time.time())
            temp = re.findall(r'(.*?)分钟', cur[0])
            if localtime.tm_hour == 0 and int(temp[0]) > localtime.tm_min:
                cur_t = datetime.date.today() - datetime.timedelta(days=1)
            else:
                cur_t = datetime.date.today()
        else:
            cur_t = datetime.date.today()
    elif len(cur) == 2:
        cur_t = datetime.date(datetime.date.today().year, int(cur[0]), int(cur[1]))
    else:
        cur_t = datetime.date(int(cur[0]), int(cur[1]), int(cur[2]))
    return cur_t


st = time.time()
# 打开存放up主个人空间网址的txt文件
if not os.path.exists("up.txt"):
    print('up.txt文件不存在')
fp = open("up.txt", "r", encoding='utf-8')
lines = fp.readlines()
fp.close()
total_up = len(lines)

# 输入时间区间
print('-输入开始时间-')
begin = time_legal()
print('-输入结束时间-')
end = time_legal()
if begin > end:
    print('时间区间不合法')

# 浏览器可用性标识符
flag = False

# 浏览器对象
driver = None

# 谷歌设置
options = ChromeOptions()
options.add_argument('--headless')  # 打开无界面模式
options.add_argument('--disable-gpu')  # 禁用gpu
options.add_argument('--user-data-dir=C:/Users/WZP/AppData/Local/Google/Chrome/User Data')  # 用户配置文件
if flag is False:
    try:
        driver = webdriver.Chrome(options=options)
    except Exception as e:
        print(e)
    else:
        flag = True

# Edge设置
options = EdgeOptions()
options.add_argument('--headless')  # 打开无界面模式
options.add_argument('--disable-gpu')  # 禁用gpu
options.add_argument('--user-data-dir=C:/Users/WZP/AppData/Local/Microsoft/Edge/User Data')  # 用户配置文件
if flag is False:
    try:
        driver = webdriver.Edge(options=options)
    except Exception as e:
        print(e)
    else:
        flag = True

if flag is False:
    print("无可用浏览器，请查看驱动程序版本是否过时！")
    exit(1)

fp = open("bookmarks.html", "w", encoding='utf-8')
fp.write(
    '<!DOCTYPE NETSCAPE-Bookmark-file-1>\n'
    '<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">\n'
    '<TITLE>Bookmarks</TITLE>\n'
    '<H1>Bookmarks</H1>\n'
    '<DL><p>\n'
    '    <DT><H3 ADD_DATE="0" LAST_MODIFIED="0">{0}-{1}</H3>\n'
    '    <DL><p>\n'.format(
        end.month, end.day))

for i in range(total_up):
    author = lines[i].split()[0]
    url = lines[i].split()[1]
    driver.get(url)
    # xpath获得视频时间
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/main/div[1]/div[2]/div/div[2]/div'))
    )
    videos = driver.find_elements(By.XPATH, '//*[@id="app"]/main/div[1]/div[2]/div/div[2]/div/div')
    for video in videos:
        video_time = video.find_element(By.CLASS_NAME, 'bili-video-card__subtitle').find_element(By.TAG_NAME, 'span').text
        cur_time = gettime(video_time)
        if cur_time < begin:
            break
        if cur_time <= end:
            video_url = video.find_element(By.CLASS_NAME, 'bili-video-card__title').find_element(By.TAG_NAME, 'a').get_attribute("href")
            video_name = video.find_element(By.CLASS_NAME, 'bili-video-card__title').find_element(By.TAG_NAME, 'a').text
            video_length = video.find_element(By.CLASS_NAME, 'bili-cover-card__stats').find_elements(By.TAG_NAME, 'div')[2].find_element(By.TAG_NAME, 'span').text
            fp.write(
                '<DT><A HREF="{0}" ADD_DATE="0" LAST_MODIFIED="0">{1}{2}{3}</A>\n'.format(
                    video_url, author, video_name, video_length))
    print('已完成{0}/{1}'.format(i + 1, total_up))

driver.quit()
fp.write('</DL><p>\n</DL><p>')
ed = time.time()
print("运行时间：" + str(datetime.timedelta(seconds=int(ed - st))))
